define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/lihua_goods/index' + location.search,
                    add_url: 'goods/lihua_goods/add',
                    edit_url: 'goods/lihua_goods/edit',
                    del_url: 'goods/lihua_goods/del',
                    multi_url: '',
                    table: 'lihua_goods',
                }
            });

            var table = $("#table");

            $.fn.bootstrapTable.locales[Table.defaults.locale]["formatSearch"] = function(){return "搜索ID";};

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                search: true,
                showToggle: false,
                showColumns: false,
                showExport: false,
                searchFormVisible: true,
                commonSearch: true,
                columns: [
                    [
                        //{checkbox: true},
                        {field: 'id', title: 'ID', operate: false},
                        {field: 'city_id', title: '城市', searchList: $.getJSON('general/lihua_city/sel'), formatter:
                            function (value, row, index) { return row.lihuacity.name;}},
                        {field: 'category_id', title: '商品分类', width: 120, searchList: $.getJSON('goods/lihua_category/sel'), formatter:
                                function (value, row, index) { return row.lihuacategory.name;}},
                        {field: 'name', title: '商品名称', align: 'left', width: 350, operate: 'LIKE', formatter: Controller.api.formatter.goods},
                        {field: 'pic', title: '商品图片', operate: false, formatter: Controller.api.formatter.image},
                        /*{field: 'original_price', title: '商品原价', operate: false, formatter: function (value, row, index) {
                            if (value > 0) {
                                return '<del>'+ value +'</del>';
                            } else {
                                return '';
                            }
                            }},*/
                        {field: 'price', title: '销售价', operate: false},
                        {field: 'sale_start', title: '销售时段', operate: false, formatter: Controller.api.formatter.sale},
                        {field: 'stock', title: '库存', operate: false, formatter: Controller.api.formatter.stock},
                        {field: 'weigh', title: '排序', operate: false},
                        {field: 'status', title: '状态', searchList: {"0":"下架","1":"在售"}, formatter: Controller.api.formatter.status},
                        {field: 'operate', title: '操作', table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 当内容渲染完成后
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-dc").data("area", ["70%", "80%"]);
                $(".btn-xc").data("area", ["600px", "450px"]);
            });

            // 监听下拉列表改变的事件
            $(document).on('change', 'select[name=city_id]', function () {
                $.getJSON('goods/lihua_category/sel?city_id='+$(this).val(), function (data) {
                    var opt = '<option value="">选择</option>';
                    $.each(data, function (k, v) {
                        opt += '<option value="'+ v.id +'">'+ v.name +'</option>';
                    });
                    $("select[name=category_id]").html(opt);
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.getCategory();
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.getCategory();
        },
        stock: function () {
            Controller.api.bindevent();

            $(document).on('click', '#enable-stock', function (e) {
                var that = this;
                var options = $.extend({}, $(that).data() || {});
                Backend.api.ajax(options, function (data) {
                    if (data === 1) {
                        $(that + ' i').removeClass('fa-rotate-180 text-gray').addClass('text-success');
                    } else {
                        $(that + ' i').removeClass('text-success').addClass('fa-rotate-180 text-gray');
                    }
                });
            });

            $(document).on('click', '#multi-set', function () {
                var num = $("#multi-num").val();
                if (num) {
                    $("#multi-num").val('');
                    $("input[id^=store_]").val(num);
                    $("input[id^=store_]").each(function () {
                        var param = {store_id: $(this).data('id'), stock_id: $(this).data('stock_id'), num: num};
                        $.post(window.location.href, param);
                    });
                    Toastr.success('批量设置成功');
                } else {
                    $("#multi-num").focus();
                }
            });

            $("input[id^=store_]").blur(function () {
                var param = {store_id: $(this).data('id'), stock_id: $(this).data('stock_id'), num: $(this).val()};
                $.post(window.location.href, param, function (ret) {
                    if (ret.code === 1) Toastr.success('修改库存成功');
                    else Toastr.error(ret.msg);
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            getCategory: function () {
                $(document).on('change', '#c-city_id', function () {
                    $.getJSON('goods/lihua_category/sel?city_id='+$(this).val(), function (data) {
                        var opt = '<option value="">选择</option>';
                        $.each(data, function (k, v) {
                            opt += '<option value="'+ v.id +'">'+ v.name +'</option>';
                        });
                        $("#c-category_id").html(opt);
                    });
                });
            },
            formatter: {
                goods: function (value, row, index) {
                    return value + ' <small class="text-warning" data-toggle="tooltip" title="简称">[' + row.short_name + ']</small><br><span style="color:#999;">' + row.description + '</span>';
                },
                sale: function (value, row, index) {
                    if (value && row.sale_end)
                        return '从 ' + value + '<br>至 ' + row.sale_end;
                    else
                        return '';
                },
                status: function (value, row, index) {
                    var title  = '点击下架';
                    var cls    = 'fa-toggle-on text-success';
                    if (value === 0) {
                        title  = '点击在售';
                        cls    = 'fa-toggle-on fa-rotate-180 text-gray';
                    }
                    return '<a style="cursor:pointer" data-url="goods/lihua_goods/status/ids/'+row.id+'" data-table-id="table" data-refresh="1" class="btn-ajax" data-toggle="tooltip" title="'+title+'"><i class="fa ' + cls + ' fa-2x"></i></a>';

                },
                stock: function (value, row, index) {
                    return '<a data-toggle="tooltip" title="设置库存（'+ row.name +'）" href="goods/lihua_goods/stock/goods_id/'+ row.id +'/city_id/'+ row.city_id +'" class="btn btn-xs btn-info btn-dialog" data-shade="0.3">库存</a>';
                },
                image: function (value, row, index) {
                    return '<img data-toggle="tooltip" title="查看大图" src="'+ value +'" class="img-thumbnail" onclick="Layer.open({type: 1, title:\'商品图片\', shadeClose: true, area:[\'500px\',\'auto\'], content: \'<img width=100% src='+ value +'>\'});" style="width:70px;padding:2px;">';
                }
            }
        }
    };
    return Controller;
});